using System;
using System.Web;
using System.Web.UI;
using System.Collections;
using System.Web.UI.WebControls;

namespace WroxControls 
{


	// Naming container for template items

	public class CollectionItem : WebControl, INamingContainer
	{

		object _dataitem;

		public object DataItem
		{
			get{ return _dataitem; }
		}

		public CollectionItem(object value)
		{
			_dataitem = value;
		}
	}

   public class ICollectionLister : WebControl, INamingContainer
											        // Step 3
   {

		// The data source the control will enumerate

		ICollection _datasource;

		public ICollection DataSource
		{
			get { return _datasource; }
			set { _datasource = value; }
		}

		// The template used for the header

		ITemplate _headingStyle;

		[TemplateContainer(typeof(ICollectionLister))]
		public ITemplate HeadingStyle
		{
			get{ return _headingStyle; }
			set{ _headingStyle = value; }
		}

		// The template used for the item

		ITemplate _itemStyle;

		[TemplateContainer(typeof(CollectionItem))]
		public ITemplate ItemStyle
		{
			get{ return _itemStyle; }
			set{ _itemStyle = value; }
		}


		// Create the child control hierarchy from viewstate only

		protected override void CreateChildControls()
		{
			int iCount = 0;
			int i;
			CollectionItem item;

			if ( _headingStyle != null )
				_headingStyle.InstantiateIn( this );

			iCount = (int) ViewState["count"];

			for( i=0; i< iCount; i++ )
			{
				if ( _itemStyle != null )
				{
					item = new CollectionItem( null );
					_itemStyle.InstantiateIn( item );
					Controls.Add( item );
				}
			}

		}

		// Create control hierarchy with the data source

		protected override void OnDataBinding( EventArgs args )
		{
				base.OnDataBinding(args);

				if ( _datasource == null )
					throw new Exception("Control requires a data source");

				
				ClearChildViewState();
	         Controls.Clear();

				// Clear all controls and state

				IEnumerator e;
				int iCount = 0;

				if ( _headingStyle != null )
					_headingStyle.InstantiateIn( this );

				e = _datasource.GetEnumerator();

				CollectionItem item;

				while( e.MoveNext() )
				{
					if ( _itemStyle != null )
					{
						item = new CollectionItem( e.Current );
						_itemStyle.InstantiateIn( item );
						Controls.Add( item );
						iCount++;

					}
				}

				// Remember the number of controls, so we can recreate the
				// same controls, without the data source.

				ViewState["count"] = iCount;
	
				// stop CreateChildControls() being called again
            ChildControlsCreated = true;		
	
				// Ensure view state is being tracked
            TrackViewState();
		}
   }
};

